package com.cunshe.web;

import com.cunshe.common.*;
import com.cunshe.domain.*;
import com.cunshe.entity.vo.CategoryVO;
import com.cunshe.entity.vo.VideoListVO;
import com.cunshe.service.*;
import com.sunkee.commons.utils.DateUtils;
import com.sunkee.commons.utils.ListUtils;
import com.sunkee.commons.utils.StringUtils;
import com.sunkee.entity.page.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/")
public class HomeController extends BaseController{

    @Autowired
    private HomeImageService homeImageService;
    @Autowired
    private CooperativeCustomersService cooperativeCustomersService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private CompanyProfileService companyProfileService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private DataDownService dataDownService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductImageService productImageService;
    @Autowired
    private VideoService videoService;

    @ModelAttribute
    public void loadMenu(Model model) {
        List<Menu> menus = menuService.all();
        menus = (List<Menu>) ListUtils.list2Tree(menus);

        CompanyProfile companyProfile = companyProfileService.get();
        int i = DateUtils.differentDays(companyProfile.getEstablishDate(), new Date());
        int year = 1;
        if(i > 1){
            year = i / 365;
        }

        String lang = Optional.ofNullable(request.getSession().getAttribute("lang"))
                .map(Object::toString)
                .orElse(LangEnum.zh.name());
        Map<String, String> i18n = I18n.getI18n(lang);

        model.addAttribute("i18n", i18n);

        model.addAttribute("companyProfile", companyProfile);
        model.addAttribute("year", year);
        model.addAttribute("page", "");
        model.addAttribute("menus", menus);
    }

    /**
     * 首页
     */
    @GetMapping("")
    public String index(Model model) {
        List<HomeImage> homeImageList = homeImageService.list(HomeImage.builder().build());
        List<HomeImage> screen1Image = new ArrayList<>();
        List<HomeImage> screen4ProduceImage = new ArrayList<>();

        HomeImage screen2 = null;
        HomeImage screen3 = null;
        HomeImage screen4 = null;
        HomeImage screen5 = null;

        List<HomeImage> screen1Link = new ArrayList<>();
        List<HomeImage> screen2Link = new ArrayList<>();
        List<HomeImage> screen4Link = new ArrayList<>();

        for (HomeImage homeImage : homeImageList) {
            if (homeImage.getScreen() == 1 && homeImage.getType() == 1) {
                screen1Link.add(homeImage);
            } else if (homeImage.getScreen() == 1 && homeImage.getType() == 2) {
                screen1Image.add(homeImage);
            } else if (homeImage.getScreen() == 2 && homeImage.getType() == 1) {
                screen2Link.add(homeImage);
            } else if (homeImage.getScreen() == 2 && homeImage.getType() == 2) {
                screen2 = homeImage;
            } else if (homeImage.getScreen() == 3 && homeImage.getType() == 2) {
                screen3 = homeImage;
            } else if (homeImage.getScreen() == 3 && homeImage.getType() == 1) {
                screen3 = homeImage;
            }else if (homeImage.getScreen() == 4 && homeImage.getType() == 2) {
                screen4 = homeImage;
            } else if (homeImage.getScreen() == 4 && homeImage.getType() == 1) {
                screen4Link.add(homeImage);
            } else if (homeImage.getScreen() == 4 && homeImage.getType() == 3) {
                screen4ProduceImage.add(homeImage);
            } else if (homeImage.getScreen() == 5) {
                screen5 = homeImage;
            }
        }

        // 合作客户
        List<CooperativeCustomers> coperativeCustomers = cooperativeCustomersService.all();

        // 推荐视频
        List<Video> video = videoService.list(Video.builder().homeRecommend(true).build());

        model.addAttribute("video", video);

        model.addAttribute("screen1Image", screen1Image);
        model.addAttribute("screen2", screen2);
        model.addAttribute("screen3", screen3);
        model.addAttribute("screen4", screen4);
        model.addAttribute("screen5", screen5);

        model.addAttribute("screen1Link", screen1Link);
        model.addAttribute("screen2Link", screen2Link);
        model.addAttribute("screen4Link", screen4Link);

        model.addAttribute("screen4ProduceImage", screen4ProduceImage);

        model.addAttribute("coperativeCustomers", coperativeCustomers);
        model.addAttribute("page", "home");
        return "index";
    }

    /**
     * 公司简介
     */
    @GetMapping(value = "company")
    public String companyProfile() {

        return "company";
    }

    /**
     * 合作客户
     */
    @GetMapping(value = "teamwork")
    public String teamwork(Model model) {
        List<CooperativeCustomers> all = cooperativeCustomersService.all();
        model.addAttribute("coperativeCustomers", all);
        return "teamwork";
    }

    /**
     * 使用案例详情
     */
    @GetMapping(value = "case_detail")
    public String case_detail(Model model) {

        return "case-detail";
    }

    private List<Menu> series(List<Menu> menus, Model model){
        List<Menu> series = new ArrayList<>(16);
        for (Menu menu : menus) {
            if(menu.getParentId() == 2){
                series.add(menu);
            }
        }
        model.addAttribute("series", series);
        return series;
    }

    /**
     * 产品列表
     */
    @GetMapping(value = "product_list")
    public String product_list(String s, Model model) {
        if (s != null) {
            s = s.trim();
        }

        List<Menu> menus = menuService.all();
        menus = series(menus, model);

        List<Product> productList = productService.list(Product.builder().category1(s).build());
        for (Product product : productList) {
            String category1 = menus.stream()
                    .filter(var -> String.valueOf(var.getId()).equals(product.getCategory1()))
                    .findFirst()
                    .map(Menu::getTitle)
                    .orElse("");
            product.setCategory1Name(category1);

            String category2 = menus.stream()
                    .filter(var -> String.valueOf(var.getId()).equals(product.getCategory2()))
                    .findFirst()
                    .map(Menu::getTitle)
                    .orElse("");
            product.setCategory2Name(category2);

        }

        model.addAttribute("productList", productList);
        return "product-list";
    }

    /**
     * 产品详情
     */
    @GetMapping(value = "product_detail_{id}")
    public String product_detail(@PathVariable(value = "id") Long id, Model model) {
        Product product = productService.get(id);

        if (product == null) {
            return null;
        }
        List<ProductImage> productImage = productImageService.getProductImage(id);
        String mainImage = "";
        if (!CollectionUtils.isEmpty(productImage)) {
            mainImage = productImage.get(0).getUrl();
        }
        List<Product> related = productService.list(Product.builder().category1(product.getCategory1()).build());

        model.addAttribute("product", product);
        model.addAttribute("productImage", productImage);
        model.addAttribute("mainImage", mainImage);
        model.addAttribute("related", related);
        return "product-detail";
    }

    /**
     * 产品视频列表
     */
    @GetMapping(value = "product_video")
    public String product_video(String s, Long p, Model model) {
        if (s != null) {
            s = s.trim();
        }
        List<Menu> menus = menuService.all();
        List<Product> productList = null;
        List<CategoryVO> category = null;
        List<String> category1 = productService.getCategory1();
        List<VideoListVO> videoList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(category1)) {
            productList = productService.list(Product.builder().build());
            List<VideoListVO> finalVideoList = videoList;
            productList = productList.stream()
                    .filter(var -> StringUtils.isNotBlank(var.getVideoUrl()))
                    .peek(product -> {
                        List<String> videoUrl = StringUtils.split(product.getVideoUrl(), ",", String.class);
                        if(!CollectionUtils.isEmpty(videoUrl)){
                            List<String> videoImageUrl = StringUtils.split(product.getVideoImageUrl(), ",", String.class);
                            for (int i = 0; i < videoUrl.size(); i++) {
                                String videoImage = "";
                                if(!CollectionUtils.isEmpty(videoImageUrl) && videoImageUrl.size() >= (i + 1) ) {
                                    videoImage = videoImageUrl.get(i);
                                }
                                VideoListVO build = VideoListVO.builder()
                                        .id(product.getId())
                                        .category(product.getCategory1())
                                        .title(product.getTitle())
                                        .titleEn(product.getTitleEn())
                                        .videoUrl(videoUrl.get(i))
                                        .videoImageUrl(videoImage)
                                        .build();
                                finalVideoList.add(build);
                            }
                        }
                    })
                    .collect(Collectors.toList());

            List<Product> finalProductList = productList;
            category = category1.stream()
                    .map(var -> {
                        Menu menu = menus.stream()
                                .filter(var1 -> var1.getId().equals(Long.parseLong(var)))
                                .findFirst()
                                .orElse(null);
                        String name = "", nameEn = "";
                        if(menu != null){
                            name = menu.getTitle();
                            nameEn = menu.getTitleEn();
                        }
                        List<Product> collect = finalProductList.stream()
                                .filter(product -> product.getCategory1().equals(var))
                                .collect(Collectors.toList());
                        return CategoryVO.builder()
                                .id(var)
                                .name(name)
                                .nameEn(nameEn)
                                .productList(collect)
                                .build();
                    })
                    .collect(Collectors.toList());

        }
        if(StringUtils.isNotBlank(s)){
            String finalS = s;
            videoList = videoList.stream()
                    .filter(videoListVO -> videoListVO.getCategory().equals(finalS))
                    .collect(Collectors.toList());
        }
        if(p != null){
            videoList = videoList.stream()
                    .filter(videoListVO -> videoListVO.getId().equals(p))
                    .collect(Collectors.toList());
        }

        model.addAttribute("category", category);
        model.addAttribute("videoList", videoList);
        return "product-video";
    }

    /**
     * 视频详情
     */
    @GetMapping(value = "video_detail_{id}")
    public String video_detail(@PathVariable(value = "id") Long id, String p, Model model) {
        Product product = productService.get(id);
        if (product == null) {
            return null;
        }
        VideoListVO video = null;
        List<String> videoUrl = StringUtils.split(product.getVideoUrl(), ",", String.class);
        if(!CollectionUtils.isEmpty(videoUrl)){
            List<String> videoImageUrl = StringUtils.split(product.getVideoImageUrl(), ",", String.class);
            for (int i = 0; i < videoUrl.size(); i++) {
                String videoImage = "";
                if(!CollectionUtils.isEmpty(videoImageUrl) && videoImageUrl.size() >= (i + 1) ) {
                    videoImage = videoImageUrl.get(i);
                }
                if(videoUrl.get(i).equals(p)){
                    video = VideoListVO.builder()
                            .id(product.getId())
                            .category(product.getCategory1())
                            .title(product.getTitle())
                            .titleEn(product.getTitleEn())
                            .videoUrl(videoUrl.get(i))
                            .videoImageUrl(videoImage)
                            .build();
                    break;
                }

            }
        }

        model.addAttribute("video", video);
        model.addAttribute("product", product);
        return "video-detail";
    }

    /**
     * 技术支持
     */
    @GetMapping(value = "technical")
    public String technical(Model model) {

        return "technical";
    }

    /**
     * 查询新闻
     * @param pageNo
     * @param type
     * @return
     */
    @GetMapping(value = "queryNew")
    @ResponseBody
    public ResponseVO<Pageable<News>> queryNew(@RequestParam("pageNo") int pageNo, @RequestParam("type") int type) {
        List<Integer> typeList = new ArrayList<>(2);
        typeList.add(type);
        if(type == DictConsts.NEWS_TYPE_1) {
            typeList.add(DictConsts.NEWS_TYPE_2);
        }
        Pageable<News> pagelist = newsService.pagelist(pageNo, 6, News.builder().typeList(typeList).build());
        return ResponseVO.success(pagelist);
    }

    /**
     * 资料下载
     */
    @GetMapping(value = "queryDown")
    @ResponseBody
    public ResponseVO download() {
        List<DataDown> dataDowns = dataDownService.all();

        return ResponseVO.success(dataDowns);
    }

    /**
     * 荣誉资质
     */
    @GetMapping(value = "honor")
    public String honor(Model model) {

        return "honor";
    }

    /**
     * 新闻
     */
    @GetMapping(value = {"news", "news_{type}"})
    public String news(@PathVariable(value = "type", required = false) Integer type, Model model) {
        List<News> news = newsService.list(News.builder().type(type).build());

        model.addAttribute("type", type);
        model.addAttribute("news", news);
        return "new-list";
    }

    /**
     * 新闻详情
     */
    @GetMapping(value = "news_detail_{id}")
    public String news_detail(@PathVariable(value = "id") Long id, Model model) {
        News news = newsService.get(id);

        model.addAttribute("news", news);
        return "news-detail";
    }

    /**
     * 联系我们
     */
    @GetMapping(value = "contact_us")
    public String contact_us(Model model) {

        return "contact-us";
    }

    /**
     * 使用案例
     */
    @GetMapping(value = "show_case")
    public String show_case(Model model) {
        List<News> news = newsService.top(3, DictConsts.NEWS_TYPE_3);
        model.addAttribute("news", news);
        return "show-case";
    }

    /**
     * 使用案例详情
     */
    @GetMapping(value = "case_detail_{id}")
    public String case_detail(@PathVariable(value = "id") Long id, Model model) {
        News news = newsService.get(id);

        model.addAttribute("news", news);
        return "case-detail";
    }

    /**
     * 切换语言
     * @param lang
     * @param request
     * @return
     */
    @GetMapping(value = "setLanguage")
    @ResponseBody
    public ResponseVO lang(@RequestParam("lang") LangEnum lang, HttpServletRequest request){
        System.out.println(lang);
        request.getSession().setAttribute("lang", lang.name());
        return ResponseVO.success();
    }

}
